package top.easyblog.core.aspect;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.easyblog.common.constant.Constants;
import top.easyblog.common.exception.DLockException;
import top.easyblog.common.response.ShortlinkResultCode;
import top.easyblog.core.annotation.DLock;
import top.easyblog.core.support.lock.DistributedLock;
import top.easyblog.core.support.lock.RedisDistributeLockFactory;
import top.easyblog.core.util.SpELUtils;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author: frank.huang
 * @date: 2023-12-21 22:19
 */
@Slf4j
@Aspect
@Component
public class RedisDistributeLockAspect {

    @Autowired
    private RedisDistributeLockFactory redisDistributeLockFactory;


    @Pointcut("@annotation(top.easyblog.core.annotation.DLock)")
    public void getDLock() {
    }


    @Around("getDLock()")
    public Object processApiRequest(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();

        if (!method.isAnnotationPresent(DLock.class)) {
            throw new DLockException(ShortlinkResultCode.DLOCK_ANNOTATION_NOT_FOUND,
                    String.format("方法[%s]签名未找到DLock注解", method.getName()));
        }

        DLock dLock = method.getAnnotation(DLock.class);
        String key = dLock.key();

        StringBuilder extKey = new StringBuilder();
        if (dLock.extKey() != null && dLock.extKey().length > 0) {
            for (String exp : dLock.extKey()) {
                extKey.append(Constants.SHARP).append(SpELUtils.parse(pjp.getTarget(), exp, method, pjp.getArgs()));
            }
        }


        final String finalKey = StringUtils.isNotBlank(extKey) ? String.format("%s-%s", key, extKey) : key;

        DistributedLock lock = dLock.waitingLock() ? redisDistributeLockFactory.getDistributedLock(finalKey) :
                redisDistributeLockFactory.getNonWaitingDistributedLock(finalKey);
        if (Objects.isNull(lock)) {
            throw new DLockException(ShortlinkResultCode.ACQUIRED_REDIS_LOCK_FAILED);
        }


        try {
            if (lock.lock()) {
                log.info("Get redis lock success >>> {}", key);
            } else {
                log.warn("Get redis lock failed >>> {}", key);
            }
            return pjp.proceed(pjp.getArgs());
        } finally {
            lock.unlock();
        }
    }

}
